<template>
  <div class="app-container sales-dashboard">
    <!-- 标题区域 -->
    <div class="dashboard-header">
      <h2 class="dashboard-title">销售情况分析</h2>
      <div class="dashboard-actions">
        <el-select v-model="yearSelected" placeholder="选择年份" @change="handleYearChange" class="year-select">
          <el-option
            v-for="year in availableYears"
            :key="year"
            :label="`${year}年`"
            :value="year"
          />
        </el-select>
        <el-select v-model="monthSelected" placeholder="选择月份" @change="handleMonthChange" class="month-select">
          <el-option
            v-for="month in availableMonths"
            :key="month"
            :label="`${month}月`"
            :value="month"
          />
        </el-select>
        <el-button type="primary" @click="refreshData" class="apple-button primary-button">
          <el-icon><Refresh /></el-icon> 刷新数据
        </el-button>
      </div>
    </div>

    <!-- 数据卡片区域 -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :xs="24" :sm="12" :md="6" v-for="(card, index) in overviewCards" :key="index">
        <el-card class="apple-card data-card" :class="card.type">
          <div class="card-icon">
            <el-icon>
              <component :is="card.icon"></component>
            </el-icon>
          </div>
          <div class="card-content">
            <span class="card-title">{{ card.title }}</span>
            <span class="card-value">{{ card.prefix }}{{ formatNumber(card.value) }}{{ card.suffix }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 左侧：月度销售额 -->
      <el-col :xs="24" :md="12">
        <el-card class="apple-card chart-card">
          <template #header>
            <div class="chart-header">
              <span>{{ yearSelected }}年月度销售额</span>
              <el-radio-group v-model="salesChartType" size="small">
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="line">折线图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="monthlySalesChart"></div>
        </el-card>
      </el-col>

      <!-- 右侧：产品销售占比 -->
      <el-col :xs="24" :md="12">
        <el-card class="apple-card chart-card">
          <template #header>
            <div class="chart-header">
              <span>{{ yearSelected }}年{{ monthSelected }}月产品销售额占比</span>
              <el-radio-group v-model="productChartType" size="small">
                <el-radio-button label="pie">饼图</el-radio-button>
                <el-radio-button label="ring">环形图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container product-ratio-chart" ref="productRatioChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行图表 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 左侧：销售趋势 -->
      <el-col :xs="24" :md="16">
        <el-card class="apple-card chart-card">
          <template #header>
            <div class="chart-header">
              <span>{{ yearSelected }}年{{ monthSelected }}月销售趋势</span>
            </div>
          </template>
          <div class="chart-container" ref="salesTrendChart"></div>
        </el-card>
      </el-col>

      <!-- 右侧：订单数量对比 -->
      <el-col :xs="24" :md="8">
        <el-card class="apple-card chart-card">
          <template #header>
            <div class="chart-header">
              <span>月度订单量</span>
            </div>
          </template>
          <div class="chart-container" ref="orderCountChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 第三行图表：年度收入 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="apple-card chart-card yearly-revenue-card">
          <template #header>
            <div class="chart-header">
              <span>近十年年度收入</span>
              <el-radio-group v-model="yearlyChartType" size="small">
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="line">折线图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="yearlyRevenueChart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Money, ShoppingCart, User, Histogram, Refresh } from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import { getMonthlySales, getProductSalesRatio, getSalesOverview, getSalesTrend, getYearlyRevenue } from '@/api/sales';

// 图表引用
const monthlySalesChart = ref(null);
const productRatioChart = ref(null);
const salesTrendChart = ref(null);
const orderCountChart = ref(null);
const yearlyRevenueChart = ref(null);

// 图表实例
let monthlySalesChartInstance = null;
let productRatioChartInstance = null;
let salesTrendChartInstance = null;
let orderCountChartInstance = null;
let yearlyRevenueChartInstance = null;

// 获取当前日期和上个月
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth() + 1; // JavaScript月份从0开始
const lastMonth = currentMonth === 1 ? 12 : currentMonth - 1;

// 年份和月份选择
const yearSelected = ref(currentYear);
const monthSelected = ref(lastMonth); // 默认显示上个月
const availableYears = [currentYear - 2, currentYear - 1, currentYear, currentYear + 1];
const availableMonths = Array.from({ length: 12 }, (_, i) => i + 1); // 1-12月

// 图表类型
const salesChartType = ref('bar');
const productChartType = ref('pie');
const yearlyChartType = ref('bar'); // 新增年度图表类型

// 数据存储
const salesData = reactive({
  monthlySales: {
    months: [],
    sales: [],
    orders: [],
    year: currentYear
  },
  productRatio: [],
  salesOverview: {
    totalSales: 0,
    monthSales: 0,
    orderCount: 0,
    monthOrderCount: 0,
    activeCustomers: 0,
    currentMonth: 0,
    currentYear: 0
  },
  salesTrend: {
    days: [],
    sales: [],
    month: lastMonth,
    year: currentYear
  },
  yearlyRevenue: {
    years: [],
    revenues: [],
  },
  loading: false
});

// 概览卡片数据
const overviewCards = reactive([
  {
    title: '上月销售总额',
    value: 0,
    prefix: '¥ ',
    suffix: '',
    icon: Money,
    type: 'primary',
    footer: '上个月度累计销售额'
  },
  {
    title: '年度销售总额',
    value: 0,
    prefix: '¥ ',
    suffix: '',
    icon: Histogram,
    type: 'success',
    footer: '当年累计销售额'
  },
  {
    title: '上月订单数',
    value: 0,
    prefix: '',
    suffix: ' 单',
    icon: ShoppingCart,
    type: 'warning',
    footer: '上个月度累计订单'
  },
  {
    title: '活跃客户数',
    value: 0,
    prefix: '',
    suffix: ' 位',
    icon: User,
    type: 'info',
    footer: '当前活跃客户总数'
  }
]);

// 监听图表类型变化
watch(salesChartType, () => {
  renderMonthlySalesChart();
});

watch(productChartType, () => {
  renderProductRatioChart();
});

// 监听年度图表类型变化
watch(yearlyChartType, () => {
  renderYearlyRevenueChart();
});

// 年份变化处理
const handleYearChange = async (year) => {
  await fetchData({ year, month: monthSelected.value });
};

// 月份变化处理
const handleMonthChange = async (month) => {
  await fetchData({ year: yearSelected.value, month });
};

// 刷新数据
const refreshData = async () => {
  await fetchData({ year: yearSelected.value, month: monthSelected.value });
  ElMessage.success('数据已刷新');
};

// 格式化数字
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0';
  
  if (num >= 10000) {
    return (num / 10000).toFixed(2) + ' 万';
  }
  
  // 确保小数仅保留两位
  return parseFloat(num).toFixed(2).replace(/\.00$/, '');
};

// 获取数据
const fetchData = async (params = {}) => {
  salesData.loading = true;
  try {
    // 获取月度销售数据
    const monthlySalesResponse = await getMonthlySales(params);
    if (monthlySalesResponse.code === 200) {
      // 处理数据，确保销售额保留两位小数
      const data = monthlySalesResponse.data;
      if (data && data.sales) {
        data.sales = data.sales.map(sale => parseFloat(parseFloat(sale).toFixed(2)));
      }
      salesData.monthlySales = data;
    }
    
    // 获取产品销售占比数据 - 确保传递月份参数
    const productRatioParams = { ...params };
    if (!productRatioParams.month && monthSelected.value) {
      productRatioParams.month = monthSelected.value;
    }
    const productRatioResponse = await getProductSalesRatio(productRatioParams);
    if (productRatioResponse.code === 200) {
      // 处理数据，确保销售额保留两位小数
      const data = productRatioResponse.data;
      if (data && Array.isArray(data)) {
        data.forEach(item => {
          if (item.sales !== undefined) {
            item.sales = parseFloat(parseFloat(item.sales).toFixed(2));
          }
          if (item.value !== undefined) {
            item.value = parseFloat(parseFloat(item.value).toFixed(2));
          }
        });
      }
      salesData.productRatio = data;
    }
    
    // 获取销售概览数据
    const salesOverviewResponse = await getSalesOverview();
    if (salesOverviewResponse.code === 200) {
      // 处理数据，确保销售额保留两位小数
      const data = salesOverviewResponse.data;
      if (data) {
        if (data.totalSales !== undefined) {
          data.totalSales = parseFloat(parseFloat(data.totalSales).toFixed(2));
        }
        if (data.monthSales !== undefined) {
          data.monthSales = parseFloat(parseFloat(data.monthSales).toFixed(2));
        }
      }
      salesData.salesOverview = data;
      
      // 更新卡片数据
      overviewCards[0].value = data.monthSales;
      overviewCards[1].value = data.totalSales;
      overviewCards[2].value = data.monthOrderCount;
      overviewCards[3].value = data.activeCustomers;
    }
    
    // 获取销售趋势数据 - 确保传递选择的月份参数
    const salesTrendParams = { ...params };
    if (!salesTrendParams.month && monthSelected.value) {
      salesTrendParams.month = monthSelected.value;
    }
    const salesTrendResponse = await getSalesTrend(salesTrendParams);
    if (salesTrendResponse.code === 200) {
      // 处理数据，确保销售额保留两位小数
      const data = salesTrendResponse.data;
      if (data && data.sales) {
        data.sales = data.sales.map(sale => parseFloat(parseFloat(sale).toFixed(2)));
      }
      salesData.salesTrend = data;
    }
    
    // 获取年度收入数据
    const yearlyRevenueResponse = await getYearlyRevenue();
    if (yearlyRevenueResponse.code === 200) {
      // 处理数据，确保销售额保留两位小数
      const data = yearlyRevenueResponse.data;
      if (data) {
        if (data.revenues) {
          data.revenues = data.revenues.map(revenue => parseFloat(parseFloat(revenue).toFixed(2)));
        }
        salesData.yearlyRevenue = data;
      }
    }
    
    // 重新渲染图表
    renderCharts();
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请稍后重试');
  } finally {
    salesData.loading = false;
  }
};

// 初始化图表
const initCharts = () => {
  // 初始化月度销售额图表
  if (monthlySalesChart.value) {
    monthlySalesChartInstance = echarts.init(monthlySalesChart.value);
    window.addEventListener('resize', () => monthlySalesChartInstance.resize());
  }
  
  // 初始化产品占比图表
  if (productRatioChart.value) {
    productRatioChartInstance = echarts.init(productRatioChart.value);
    window.addEventListener('resize', () => productRatioChartInstance.resize());
  }
  
  // 初始化销售趋势图表
  if (salesTrendChart.value) {
    salesTrendChartInstance = echarts.init(salesTrendChart.value);
    window.addEventListener('resize', () => salesTrendChartInstance.resize());
  }
  
  // 初始化订单数量图表
  if (orderCountChart.value) {
    orderCountChartInstance = echarts.init(orderCountChart.value);
    window.addEventListener('resize', () => orderCountChartInstance.resize());
  }
  
  // 初始化年度收入图表
  if (yearlyRevenueChart.value) {
    yearlyRevenueChartInstance = echarts.init(yearlyRevenueChart.value);
    window.addEventListener('resize', () => yearlyRevenueChartInstance.resize());
  }
};

// 渲染所有图表
const renderCharts = () => {
  renderMonthlySalesChart();
  renderProductRatioChart();
  renderSalesTrendChart();
  renderOrderCountChart();
  renderYearlyRevenueChart();
};

// 渲染月度销售额图表
const renderMonthlySalesChart = () => {
  if (!monthlySalesChartInstance) return;

  const { months, sales } = salesData.monthlySales;
  const isBarChart = salesChartType.value === 'bar';
  
  const option = {
    title: {
      text: `${yearSelected.value}年月度销售额`,
      left: 'center',
      top: 0,
      textStyle: {
        color: '#666',
        fontSize: 14,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        // 确保销售额只显示两位小数
        const value = parseFloat(params[0].value).toFixed(2);
        return `${params[0].name}<br/>${params[0].seriesName}: ${value} 元`;
      },
      axisPointer: {
        type: isBarChart ? 'shadow' : 'line'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%', // 增加顶部空间，为标题和数据标签留出位置
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        interval: 0, // 显示所有标签
        rotate: 0    // 不旋转
      }
    },
    yAxis: {
      type: 'value',
      name: '销售额(元)',
      axisLabel: {
        formatter: (value) => {
          if (value >= 10000) {
            return (value / 10000).toFixed(2) + '万';
          }
          return parseFloat(value).toFixed(2);
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed' // 虚线网格
        }
      }
    },
    series: [
      {
        name: '销售额',
        type: salesChartType.value,
        data: sales,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#0071e3' },
            { offset: 1, color: '#4dabf7' }
          ])
        },
        label: {
          show: true,
          position: isBarChart ? 'top' : 'top',
          formatter: (params) => {
            // 确保销售额只显示两位小数，处理大数值
            const value = params.value;
            if (value >= 1000000) { // 超过100万
              return (value / 1000000).toFixed(2) + 'M';
            } else if (value >= 10000) { // 超过1万
              return (value / 10000).toFixed(2) + 'w';
            }
            return parseFloat(value).toFixed(2);
          },
          fontSize: 12,
          color: '#333',
          fontWeight: isBarChart ? 'normal' : 'bold',
          backgroundColor: isBarChart ? 'rgba(255, 255, 255, 0.7)' : 'transparent',
          borderRadius: 4,
          padding: isBarChart ? [2, 4] : [0, 0],
          distance: isBarChart ? 5 : 8,
          align: 'center',
          verticalAlign: 'middle',
          offset: isBarChart ? [0, 0] : [0, -10]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#1a82e2' },
              { offset: 1, color: '#58b2ff' }
            ])
          },
          label: {
            show: true,
            fontWeight: 'bold',
            fontSize: 13,
            backgroundColor: isBarChart ? 'rgba(255, 255, 255, 0.9)' : 'transparent',
            color: '#0071e3'
          }
        },
        // 折线图特有配置
        smooth: salesChartType.value === 'line',
        showSymbol: salesChartType.value === 'line',
        symbolSize: salesChartType.value === 'line' ? 8 : 4,
        lineStyle: salesChartType.value === 'line' ? {
          width: 3,
          shadowColor: 'rgba(0,0,0,0.3)',
          shadowBlur: 10,
          shadowOffsetY: 8
        } : undefined,
        // 柱状图特有配置
        barWidth: salesChartType.value === 'bar' ? '60%' : undefined,
        // 区域配置
        areaStyle: salesChartType.value === 'line' ? {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 113, 227, 0.5)' },
            { offset: 1, color: 'rgba(0, 113, 227, 0.1)' }
          ])
        } : undefined
      }
    ],
    animationDuration: 1000
  };
  
  monthlySalesChartInstance.setOption(option);
};

// 渲染产品销售占比图表
const renderProductRatioChart = () => {
  if (!productRatioChartInstance) return;

  const isPie = productChartType.value === 'pie';
  
  // 获取原始数据
  let productData = [...salesData.productRatio];
  
  // 按销售额降序排序
  productData.sort((a, b) => b.sales - a.sales);
  
  // 只取前10个产品
  let displayData = productData;
  if (productData.length > 10) {
    displayData = productData.slice(0, 10);
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        // 确保销售额和百分比都只有两位小数
        const amount = parseFloat(params.value).toFixed(2);
        const percentage = params.percent.toFixed(2);
        return `<div style="font-weight:bold;margin-bottom:3px;">${params.seriesName}</div>` +
               `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color}"></span>` +
               `${params.name}<br/>` +
               `金额: ¥<span style="font-weight:bold;">${amount}</span><br/>` +
               `占比: <span style="font-weight:bold;">${percentage}%</span>`;
      }
    },
    legend: {
      type: 'scroll', // 启用滚动
      orient: 'horizontal',
      top: 0,  // 改为顶部位置
      left: 'center', 
      width: '90%',
      padding: [5, 5, 15, 5],  // 增加下方内边距，与饼图保持距离
      itemGap: 15,
      pageButtonItemGap: 5,
      pageButtonGap: 5,
      pageButtonPosition: 'end',
      pageFormatter: '{current}/{total}',
      formatter: (name) => {
        // 查找对应的产品数据
        const item = displayData.find(item => item.name === name);
        if (item && item.sales !== undefined) {
          // 格式化销售额显示，大于1万的显示为"x万"，小数只保留两位
          let salesText;
          if (item.sales >= 10000) {
            salesText = (item.sales / 10000).toFixed(2) + '万';
          } else {
            salesText = parseFloat(item.sales).toFixed(2);
          }
          // 产品名和金额
          return `${name}: ¥${salesText}`;
        }
        return name;
      },
      textStyle: {
        fontSize: 12 // 减小字体大小
      }
    },
    title: {
      text: `${yearSelected.value}年${monthSelected.value}月产品销售额TOP${displayData.length}`,
      left: 'center',
      top: 'bottom',
      textStyle: {
        color: '#666',
        fontSize: 14,
        fontWeight: 'normal'
      }
    },
    series: [
      {
        name: '产品销售额',
        type: 'pie',
        radius: isPie ? '55%' : ['40%', '60%'], // 稍微缩小半径，为外部标签留出空间
        center: ['50%', '60%'],  // 进一步向下移动中心点，为标签留出更多空间
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside', // 标签显示在外部
          formatter: (params) => {
            // 显示产品名称和百分比
            const name = params.name;
            const percent = params.percent.toFixed(2);
            
            // 不再截断名称，而是让它自动换行
            return `${name}\n${percent}%`;
          },
          fontSize: 12,
          fontWeight: 'normal',
          color: '#333',
          backgroundColor: 'rgba(255, 255, 255, 0.7)',
          borderRadius: 4,
          padding: [4, 6],
          distanceToLabelLine: 5, // 连接线到标签文本的距离
          lineHeight: 18, // 行高
          width: 120, // 设置最大宽度
          overflow: 'break', // 文本超出宽度时换行
          align: 'center' // 文本居中对齐
        },
        labelLine: {
          show: true, // 显示标签连接线
          length: 15, // 第一段长度
          length2: 10, // 第二段长度
          smooth: true, // 平滑线条
          lineStyle: {
            width: 1,
            type: 'solid'
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold',
            formatter: (params) => {
              return `${params.name}\n${params.percent.toFixed(2)}%`;
            }
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: displayData.map(item => ({
          name: item.name,
          value: parseFloat(parseFloat(item.sales || 0).toFixed(2)),  // 使用销售额作为数值并确保两位小数
          percentage: parseFloat(parseFloat(item.value || 0).toFixed(2))  // 保存百分比，可能在其他地方需要
        }))
      }
    ],
    animationDuration: 1000
  };
  
  productRatioChartInstance.setOption(option);
};

// 渲染销售趋势图表
const renderSalesTrendChart = () => {
  if (!salesTrendChartInstance) return;

  const { days, sales } = salesData.salesTrend;
  
  const option = {
    title: {
      text: `${yearSelected.value}年${monthSelected.value}月销售趋势`,
      left: 'center',
      top: 0,
      textStyle: {
        color: '#666',
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        // 确保销售额只显示两位小数
        const value = parseFloat(params[0].value).toFixed(2);
        return `${params[0].name}日<br/>${params[0].seriesName}: ${value} 元`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: days.map(day => `${day}`),
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '销售额(元)',
      axisLabel: {
        formatter: (value) => {
          if (value >= 10000) {
            return (value / 10000).toFixed(2) + '万';
          }
          return parseFloat(value).toFixed(2);
        }
      }
    },
    visualMap: {
      show: false,
      pieces: [
        {
          gt: 0,
          lte: 20000,
          color: '#bbe4ff'
        },
        {
          gt: 20000,
          lte: 30000,
          color: '#97d3fb'
        },
        {
          gt: 30000,
          lte: 40000,
          color: '#5ab8fa'
        },
        {
          gt: 40000,
          color: '#0071e3'
        }
      ]
    },
    series: [
      {
        name: '销售额',
        type: 'bar',
        data: sales,
        barWidth: '60%'
      }
    ],
    animationDuration: 1000
  };
  
  salesTrendChartInstance.setOption(option);
};

// 渲染订单数量图表
const renderOrderCountChart = () => {
  if (!orderCountChartInstance) return;

  const { months, orders } = salesData.monthlySales;
  
  // 将年月的表述添加到标题中
  const title = `${yearSelected.value}年月度订单量`;
  
  const option = {
    title: {
      text: title,
      left: 'center',
      top: 0,
      textStyle: {
        color: '#666',
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} 单'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%', // 为标题留出空间
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '订单数'
    },
    series: [
      {
        name: '订单数量',
        type: 'line',
        data: orders,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#ff9500'
        },
        lineStyle: {
          width: 3,
          color: '#ff9500'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(255, 149, 0, 0.5)' },
            { offset: 1, color: 'rgba(255, 149, 0, 0.1)' }
          ])
        },
        markLine: {
          silent: true,
          data: [
            {
              xAxis: monthSelected.value - 1, // 月份从1开始，数组索引从0开始
              lineStyle: {
                color: '#0071e3',
                width: 2,
                type: 'dashed'
              },
              label: {
                formatter: `${monthSelected.value}月`,
                position: 'start'
              }
            }
          ]
        }
      }
    ],
    animationDuration: 1000
  };
  
  orderCountChartInstance.setOption(option);
};

// 渲染年度收入图表
const renderYearlyRevenueChart = () => {
  if (!yearlyRevenueChartInstance) return;
  
  let { years, revenues } = salesData.yearlyRevenue;
  
  // 过滤掉没有数据的年份（收入为0的年份）
  const filteredData = years.map((year, index) => {
    return {
      year: year,
      revenue: revenues[index]
    };
  }).filter(item => item.revenue > 0);
  
  // 如果没有数据，添加默认提示
  if (filteredData.length === 0) {
    yearlyRevenueChartInstance.setOption({
      title: {
        text: '年度收入',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      graphic: {
        type: 'text',
        left: 'center',
        top: 'center',
        style: {
          text: '暂无收入数据',
          fontSize: 20,
          fontWeight: 'bold',
          fill: '#ccc'
        }
      }
    });
    return;
  }
  
  // 从过滤后的数据中提取年份和收入
  const filteredYears = filteredData.map(item => item.year);
  const filteredRevenues = filteredData.map(item => item.revenue);
  
  // 如果数据超过5年，只取最近5年的数据
  let displayYears = filteredYears;
  let displayRevenues = filteredRevenues;
  
  if (filteredYears.length > 5) {
    const startIndex = filteredYears.length - 5;
    displayYears = filteredYears.slice(startIndex);
    displayRevenues = filteredRevenues.slice(startIndex);
  }
  
  const isBar = yearlyChartType.value === 'bar';
  
  const option = {
    title: {
      text: `年度收入`,
      left: 'center',
      top: 0,
      textStyle: {
        color: '#666',
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        // 确保收入额只显示两位小数
        const value = parseFloat(params[0].value).toFixed(2);
        return `${params[0].name}年<br/>${params[0].seriesName}: ${value} 元`;
      },
      axisPointer: {
        type: isBar ? 'shadow' : 'line'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '8%', // 增加底部边距，确保有足够空间显示x轴标签
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: displayYears,
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        interval: 0, // 显示所有标签
        rotate: 0,   // 不旋转
        margin: 15,  // 增加与坐标轴的距离
        textStyle: {
          color: '#333', // 更深的标签颜色
          fontSize: 12,   // 适当的字体大小
          fontWeight: 'normal'
        },
        formatter: (value) => {
          return value + '年'; // 为每个年份添加"年"字
        }
      },
      axisLine: {
        lineStyle: {
          color: '#999' // 坐标轴颜色
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '收入(元)',
      axisLabel: {
        formatter: (value) => {
          if (value >= 1000000) {
            return (value / 1000000).toFixed(1) + 'M';
          } else if (value >= 10000) {
            return (value / 10000).toFixed(1) + '万';
          }
          return parseFloat(value).toFixed(0);
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '年度收入',
        type: yearlyChartType.value,
        data: displayRevenues,
        itemStyle: {
          color: function(params) {
            // 创建渐变色，近年表现更明亮
            const colorList = [
              '#91cc75', '#91cc85', '#91cc95', '#91cca5', 
              '#81ccb5', '#71ccc5', '#61ccd5', '#51cce5',
              '#41ccf5', '#31cc75', '#21ccb5', '#11ccf5'
            ];
            return colorList[params.dataIndex % colorList.length];
          }
        },
        label: {
          show: true,
          position: isBar ? 'top' : 'top',
          formatter: (params) => {
            // 格式化大数值显示
            const value = params.value;
            if (value >= 1000000) {
              return (value / 1000000).toFixed(1) + 'M';
            } else if (value >= 10000) {
              return (value / 10000).toFixed(1) + 'w';
            }
            return parseFloat(value).toFixed(0);
          },
          fontSize: 12,
          color: '#333',
          fontWeight: 'normal'
        },
        // 折线图特有配置
        smooth: yearlyChartType.value === 'line',
        showSymbol: yearlyChartType.value === 'line',
        symbolSize: yearlyChartType.value === 'line' ? 8 : 4,
        // 柱状图特有配置
        barWidth: yearlyChartType.value === 'bar' ? '50%' : undefined,
        // 折线图区域样式
        areaStyle: yearlyChartType.value === 'line' ? {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(145, 204, 117, 0.5)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
          ])
        } : undefined
      }
    ],
    animationDuration: 1000
  };
  
  yearlyRevenueChartInstance.setOption(option);
};

// 组件挂载后初始化
onMounted(async () => {
  // 等待DOM渲染完成
  await nextTick();
  
  // 设置默认选择上个月
  const today = new Date();
  const thisYear = today.getFullYear();
  let thisMonth = today.getMonth() + 1; // JavaScript月份从0开始
  
  // 计算上个月及其年份
  let prevMonth, prevYear;
  if (thisMonth === 1) {
    prevMonth = 12;
    prevYear = thisYear - 1;
  } else {
    prevMonth = thisMonth - 1;
    prevYear = thisYear;
  }
  
  // 设置默认值
  yearSelected.value = prevYear;
  monthSelected.value = prevMonth;
  
  // 初始化图表
  initCharts();
  
  // 获取数据并渲染图表，明确传递年月参数
  await fetchData({ year: prevYear, month: prevMonth });
});
</script>

<style scoped>
.sales-dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dashboard-title {
  font-size: 24px;
  color: #333;
  margin: 0;
  font-weight: 600;
}

.dashboard-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.year-select {
  width: 120px;
}

.month-select {
  width: 120px;
}

/* 数据卡片样式 */
.dashboard-cards {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
  display: flex;
  align-items: center;
  overflow: hidden;
  position: relative;
  border-radius: 12px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
  transition: all 0.3s ease;
  margin-bottom: 20px;
  padding: 20px;
}

.data-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1) !important;
}

.data-card .card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 12px;
  margin-right: 20px;
  background-color: rgba(255, 255, 255, 0.2);
  flex-shrink: 0;
}

.data-card .card-icon .el-icon {
  font-size: 30px;
  color: #fff;
}

.data-card .card-content {
  display: flex;
  flex-direction: row; /* 水平排列 */
  align-items: center; /* 垂直居中对齐 */
  justify-content: space-between; /* 两端对齐 */
  flex-grow: 1;
  height: 100%;
  overflow: hidden;
}

.data-card .card-title {
  font-size: 18px;
  color: #fff;
  font-weight: 600;
  margin-right: 10px;
  white-space: nowrap;
}

.data-card .card-value {
  font-size: 24px;
  font-weight: 700;
  color: #fff;
  white-space: nowrap;
  margin-left: auto; /* 推到右侧 */
}

.data-card .card-footer {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  white-space: nowrap; /* 保持在一行 */
}

/* 卡片类型样式 */
.data-card.primary {
  background: linear-gradient(to right, #0071e3, #4dabf7);
}

.data-card.success {
  background: linear-gradient(to right, #34c759, #7ae19e);
}

.data-card.warning {
  background: linear-gradient(to right, #ff9500, #ffbd49);
}

.data-card.info {
  background: linear-gradient(to right, #5856d6, #807df4);
}

/* 图表卡片样式 */
.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 12px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
  transition: all 0.3s ease;
  height: calc(100% - 20px); /* 使卡片高度充满父容器 */
  display: flex;
  flex-direction: column;
}

.chart-card:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1) !important;
}

.chart-card .el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 15px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.chart-container {
  height: 450px; /* 增加高度，从400px改为450px */
  width: 100%;
  flex: 1; /* 使图表容器充满卡片剩余空间 */
}

/* 针对产品占比图表特别设置 */
.product-ratio-chart {
  height: 480px; /* 保持高度 */
  position: relative;
  padding-top: 40px; /* 为顶部图例留出空间，替换原来的底部padding */
  padding-bottom: 0; /* 移除底部padding */
}

/* 按钮样式 */
.apple-button {
  border-radius: 8px !important;
  font-weight: 500 !important;
  transition: background-color 0.3s, transform 0.1s !important;
  border: none !important;
  padding: 8px 16px !important;
  display: flex;
  align-items: center;
  gap: 5px;
}

.primary-button {
  background-color: #0071e3 !important;
  color: white !important;
}

.primary-button:hover {
  background-color: #0077ed !important;
  transform: translateY(-2px);
}

.primary-button:active {
  transform: translateY(0);
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .dashboard-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .data-card {
    height: 160px; /* 在小屏幕上增加卡片高度 */
    margin-bottom: 15px;
  }
  
  .data-card .card-title,
  .data-card .card-value,
  .data-card .card-footer {
    max-width: 100%; /* 确保文本在小屏幕上能够完整显示 */
  }
  
  .yearly-revenue-card {
    height: 400px; /* 小屏幕上减少高度 */
  }
}

/* 在超小屏幕上进一步优化卡片布局 */
@media screen and (max-width: 576px) {
  .data-card {
    height: auto; /* 自动高度适应内容 */
    min-height: 160px;
    padding: 20px 15px;
  }
  
  .data-card .card-icon {
    width: 50px;
    height: 50px;
    margin-right: 10px;
  }
  
  .data-card .card-title {
    font-size: 14px;
  }
  
  .data-card .card-value {
    font-size: 20px;
  }
}

/* 年度收入图表卡片样式 */
.yearly-revenue-card {
  margin-top: 10px;
  height: 500px; /* 增加高度，确保图表有足够空间 */
}
</style>

<style>
/* 确保只有app-container有滚动条 */
.app-container {
  padding: 20px;
  height: auto;
  min-height: calc(100vh - 84px);
  overflow-y: auto !important; /* 只在这里允许纵向滚动 */
  overflow-x: hidden !important; /* 防止水平滚动 */
}

/* 优化卡片内容显示 */
.el-card__body {
  overflow: visible !important; /* 允许内容显示 */
}

/* 图表容器设置 */
.chart-container {
  overflow: visible !important; /* 允许内容完全显示 */
}

/* 小屏幕优化 */
@media screen and (max-width: 576px) {
  .apple-button {
    padding: 8px 12px !important;
    font-size: 13px !important;
  }
  
  .table-pagination {
    overflow-x: auto;
    padding-bottom: 5px;
  }
  
  .apple-pagination {
    justify-content: center;
  }
}
</style> 